﻿using System.Collections.Generic;

using Vestras.StarCraft2.Luna.Parser.Ast;

namespace Vestras.StarCraft2.Luna.Parser {
    public static class NamedEntityRegistre {
        static IDictionary<string, IList<Entity>> entities = new Dictionary<string, IList<Entity>>();

        public static IDictionary<string, IList<Entity>> Entities {
            get { return entities; }
        }

        public static IEnumerable<Entity> GetEntitiesWithName(string name) {
            if (!entities.ContainsKey(name)) {
                return null;
            }

            return entities[name];
        }

        public static void Add(string name, Entity entity) {
            IList<Entity> list;
            if (!entities.ContainsKey(name)) {
                list = new List<Entity>();
                list.Add(entity);
                entities.Add(name, list);
                return;
            }

            list = entities[name];
            if (list.Count == 1 && list[0] is Function && entity is Function) {
                Function existingFunction = list[0] as Function;
                Function addingFunction = entity as Function;
                if (existingFunction.IsPrototype) {
                    list.Remove(existingFunction);
                    addingFunction.Prototype = existingFunction;
                    list.Add(addingFunction);
                } else if (addingFunction.IsPrototype) {
                    existingFunction.Prototype = addingFunction;
                }
            } else {
                list.Add(entity);
            }

            entities[name] = list;
        }

        public static void Clear() {
            entities.Clear();
        }
    }
}
